package com.dfzt.myutils.common.file;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class CsvFileUtil {
    /**
     * 替换CSV文件中的指定列
     * @param inputFilePath 输入文件路径
     * @param outputFilePath 输出文件路径
     * @param columName 列名称
     * @param targetText 需要替换的文本
     * @param replacementText 替换的文本
     */
    public static void replaceText(String inputFilePath,String outputFilePath,String columName,String targetText,String replacementText){
        try {
            // 读取CSV文件内容
            List<String> lines = Files.readAllLines(Paths.get(inputFilePath));
            if (lines.isEmpty()) {
                throw new IllegalArgumentException("Input file is empty.");
            }

            // 获取列索引
            String[] header = lines.get(0).split(",");
            int columnIndex = -1;
            for (int i = 0; i < header.length; i++) {
                if (header[i].trim().equals(columName)) {
                    columnIndex = i;
                    break;
                }
            }
            if (columnIndex == -1) {
                throw new IllegalArgumentException("Column name not found in the CSV file.");
            }

            // 处理每一行数据
            List<String> modifiedLines = new ArrayList<>();
            modifiedLines.add(lines.get(0)); // 添加表头
            for (int i = 1; i < lines.size(); i++) {
                String[] columns = lines.get(i).split(",");
                if (columns.length > columnIndex && columns[columnIndex].trim().equals(targetText)) {
                    columns[columnIndex] = replacementText;
                }
                modifiedLines.add(String.join(",", columns));
            }

            // 写入到输出文件
            Files.write(Paths.get(outputFilePath), modifiedLines);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
